<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/27
 * Time: 上午11:30
 */

namespace Superadmin\Controller;


use Think\Image;
use Think\Upload;

class UploadController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        //区分上传路径
        $cate = I('get.cate');
        $save_conf = C('upload_path.'.$cate);
        $save_path = $save_conf['path'];
       // new Image()
        $upload = new Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     $save_path; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        $upload->autoSub  =     true;
        $upload->subName  =     array('date','Ymd');
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $data = array(
                'status' => 0,
                'msg'    => $upload->getError(),
                'data'   => '',
            );
            $this->ajaxReturn($data);
        }else{// 上传成功
          //  $this->success('上传成功！');
            //生成缩略图
            if($save_conf['thumb'])
            {
                $image_path = $save_path  .$info['file']['savepath'];
                $image_name = $info['file']['savename'];
                $thumb_config = array(
                    'width'    => 100,
                    'height'   => 300,
                    'type'     => Image::IMAGE_THUMB_SCALE,
                );
                $this->createThumb($image_path, $image_name, $thumb_config);
            }
            $data = array(
                'status' => 0,
                'msg'    => $upload->getError(),
                'data'   => $info,
            );
            $this->ajaxReturn($data);
        }
    }

    //生成缩略图
    public function createThumb($image_path, $image_name, $config)
    {
        $image = new Image();
        $image->open($image_path.$image_name);
        //生成缩略图
        $save_name = str_replace('.','_'.$config['width'].'x'.$config['height'].'.', $image_name);
        $image->thumb($config['width'], $config['height'], $config['type'])->save($image_path.'/'.$save_name);
    }
}